package xyz.scootaloo.oj.leetcode

import org.junit.Test
import xyz.scootaloo.common.TestDsl

/**
 * @author flutterdash@qq.com
 * @since 2021/7/9 14:01
 */
class P350 : TestDsl {

    private fun intersect(nums1: IntArray, nums2: IntArray): IntArray {
        fun getIntersect(shorter: IntArray, larger: IntArray): IntArray {
            val minMap = HashMap<Int, Int>()
            for (num in shorter) {
                val count = minMap[num]
                if (count != null) {
                    minMap[num] = count + 1
                } else {
                    minMap[num] = 1
                }
            }

            val intersection = ArrayList<Int>()
            for (num in larger) {
                val count = minMap.getOrDefault(num, 0)
                if (count > 0) {
                    intersection.add(num)
                    minMap[num] = count - 1
                }
            }

            return intersection.stream().mapToInt {num -> num}.toArray() ?: intArrayOf()
        }

        return if (nums1.size < nums2.size) {
            getIntersect(nums1, nums2)
        } else {
            getIntersect(nums2, nums1)
        }
    }

    @Test
    fun test0() {
        intersect(intArrayOf(1, 2, 2, 1), intArrayOf(2, 2)).log()
        intersect(intArrayOf(1, 2, 2, 1), intArrayOf(2)).log()
    }

}
